package com.shchekoldin.juliet.packager.plugins;

import com.shchekoldin.juliet.packager.utils.FilesIterator;
import com.shchekoldin.juliet.packager.utils.FilesIteratorEvent;
import com.shchekoldin.juliet.packager.xml.GroupElement;
import com.yahoo.platform.yui.compressor.YUICompressor;
import org.w3c.dom.Element;

import java.io.File;

public class GlobalFilesOptimizer implements PackagerPlugin {

    private GroupElement group;

    // -------------------------------------------------------
    // -                        LOGIC                        -
    // -------------------------------------------------------

    private void subscribeOnFilesIteratorEvents(final FilesIterator filesIterator) {
        filesIterator.getOnFinish().add(new FilesIteratorEvent() {
            @Override
            public void run() { optimize(); }
        });
    }

    private void optimize() {
        Element optimizeOption = group.getCustomOption("optimize");

        if (optimizeOption == null) return;

        String outputDir = group.getOutputDir();
        String optimizeFilePath = outputDir + "/" + group.getName() + group.getFilesExtension();
        String postfix = optimizeOption.getAttribute("postfix");
        boolean removeSource = Boolean.valueOf(optimizeOption.getAttribute("removeSource"));

        // Skip css optimization.
        if (group.getFilesExtension().indexOf("css") != -1) {
            File cssFile = new File(optimizeFilePath);
            cssFile.renameTo(new File(outputDir + "/" + group.getName() + postfix + group.getFilesExtension()));
            return;
        }

        String[] commands = new String[] {
            optimizeFilePath,
            "-o",
            outputDir + "/" + group.getName() + postfix + group.getFilesExtension(),
            "--charset",
            "utf-8"
        };

        YUICompressor.main(commands);

        if (removeSource) {
            File sourceFile = new File(optimizeFilePath);
            sourceFile.delete();
        }
    }

    //
    // API
    //

    @Override
    public void initialize(FilesIterator filesIterator) {
        this.group = filesIterator.getGroup();
        subscribeOnFilesIteratorEvents(filesIterator);
    }

}
